package org.sidora.strata.feature;

import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.Serializable;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
import javax.swing.DefaultListModel;
import javax.swing.JCheckBoxMenuItem;
import javax.swing.JMenu;
import javax.swing.JPopupMenu;
import javax.swing.SwingWorker;
import javax.swing.UIManager;
import org.openide.ErrorManager;
import org.openide.util.NbBundle;
import org.openide.util.Utilities;
import org.openide.windows.TopComponent;
import org.openide.windows.WindowManager;
import org.sidora.core.Action;
import org.sidora.core.Feature;
import org.sidora.core.Sector;
import org.sidora.core.context.Context;
import org.sidora.core.util.AbstractInventory;
import org.sidora.strata.SidoraTools;
import org.sidora.strata.Storage;


/**
 * Feature Form
 * @author Enric Tartera, Juan Manuel Gimeno, Roger Masgoret
 * @version 1.0
 */
final class FeatureTopComponent extends TopComponent {
    
    private static FeatureTopComponent instance;
    /** path to the icon used by the component and its open action */
    static final String ICON_PATH = "org/sidora/resources/feature16.png";;
    
    private static final String PREFERRED_ID = "FeatureTopComponent";
    
    private FeatureTopComponent() {
        
        System.setProperty(
            "Quaqua.tabLayoutPolicy","wrap"
         );
         // set the Quaqua Look and Feel in the UIManager
         try { 
              UIManager.setLookAndFeel(
                  "ch.randelshofer.quaqua.QuaquaLookAndFeel"
              );
         // set UI manager properties here that affect Quaqua
         
         } catch (Exception e) {
             // take an appropriate action here
             
         }
        
        initComponents();
        setName(NbBundle.getMessage(FeatureTopComponent.class, "CTL_FeatureTopComponent"));
        setToolTipText(NbBundle.getMessage(FeatureTopComponent.class, "HINT_FeatureTopComponent"));
        setIcon(Utilities.loadImage(ICON_PATH, true));
    }
    
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jTextFieldSector = new javax.swing.JTextField();
        jLabel4 = new javax.swing.JLabel();
        jLabel7 = new javax.swing.JLabel();
        jLabel6 = new javax.swing.JLabel();
        jTextFieldFeature = new javax.swing.JTextField();
        jTextFieldAction = new javax.swing.JTextField();
        jLabel8 = new javax.swing.JLabel();
        jTextFieldFeatureType = new javax.swing.JTextField();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jListComposition = new javax.swing.JList();
        jListComposition.putClientProperty(
            "Quaqua.List.style", "striped"
        );
        jScrollPane2 = new javax.swing.JScrollPane();
        jListRelatedContext = new javax.swing.JList();
        jListRelatedContext.putClientProperty(
            "Quaqua.List.style", "striped"
        );
        jScrollPane3 = new javax.swing.JScrollPane();
        jListRelatedFeature = new javax.swing.JList();
        jListRelatedFeature.putClientProperty(
            "Quaqua.List.style", "striped"
        );
        jLabel5 = new javax.swing.JLabel();
        jScrollPane4 = new javax.swing.JScrollPane();
        jTextAreaCommentary = new javax.swing.JTextArea();

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Definition"));

        jTextFieldSector.setEditable(false);
        jTextFieldSector.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jTextFieldSectorMouseClicked(evt);
            }
        });

        org.openide.awt.Mnemonics.setLocalizedText(jLabel4, "Sector");

        org.openide.awt.Mnemonics.setLocalizedText(jLabel7, "Feature:");

        org.openide.awt.Mnemonics.setLocalizedText(jLabel6, "Action:");

        jTextFieldFeature.setEditable(false);

        jTextFieldAction.setEditable(false);
        jTextFieldAction.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jTextFieldActionMouseClicked(evt);
            }
        });

        org.openide.awt.Mnemonics.setLocalizedText(jLabel8, "Type:");

        jTextFieldFeatureType.setEditable(false);
        jTextFieldFeatureType.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jTextFieldFeatureTypeMouseClicked(evt);
            }
        });

        org.jdesktop.layout.GroupLayout jPanel1Layout = new org.jdesktop.layout.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jPanel1Layout.createSequentialGroup()
                .add(20, 20, 20)
                .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
                    .add(jLabel7)
                    .add(jLabel8))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING, false)
                    .add(org.jdesktop.layout.GroupLayout.LEADING, jTextFieldFeature)
                    .add(org.jdesktop.layout.GroupLayout.LEADING, jTextFieldFeatureType, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 163, Short.MAX_VALUE))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(org.jdesktop.layout.GroupLayout.TRAILING, jLabel4)
                    .add(org.jdesktop.layout.GroupLayout.TRAILING, jLabel6))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
                    .add(jTextFieldSector, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 257, Short.MAX_VALUE)
                    .add(jTextFieldAction, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 257, Short.MAX_VALUE))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(jLabel7)
                    .add(jTextFieldSector, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .add(jLabel4)
                    .add(jTextFieldFeature, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(jTextFieldAction, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .add(jLabel6)
                    .add(jTextFieldFeatureType, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .add(jLabel8))
                .addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        org.openide.awt.Mnemonics.setLocalizedText(jLabel1, "Composition:");

        org.openide.awt.Mnemonics.setLocalizedText(jLabel2, "Related Context:");

        org.openide.awt.Mnemonics.setLocalizedText(jLabel3, "Related Feature:");

        jListComposition.setModel(new javax.swing.AbstractListModel() {
            String[] strings = { "Artículo 1", "Artículo 2", "Artículo 3", "Artículo 4", "Artículo 5" };
            public int getSize() { return strings.length; }
            public Object getElementAt(int i) { return strings[i]; }
        });
        jListComposition.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jListCompositionMouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(jListComposition);

        jListRelatedContext.setModel(new javax.swing.AbstractListModel() {
            String[] strings = { "Artículo 1", "Artículo 2", "Artículo 3", "Artículo 4", "Artículo 5" };
            public int getSize() { return strings.length; }
            public Object getElementAt(int i) { return strings[i]; }
        });
        jListRelatedContext.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jListRelatedContextMouseClicked(evt);
            }
        });
        jScrollPane2.setViewportView(jListRelatedContext);

        jListRelatedFeature.setModel(new javax.swing.AbstractListModel() {
            String[] strings = { "Artículo 1", "Artículo 2", "Artículo 3", "Artículo 4", "Artículo 5" };
            public int getSize() { return strings.length; }
            public Object getElementAt(int i) { return strings[i]; }
        });
        jListRelatedFeature.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jListRelatedFeatureMouseClicked(evt);
            }
        });
        jScrollPane3.setViewportView(jListRelatedFeature);

        org.openide.awt.Mnemonics.setLocalizedText(jLabel5, "Commentary:");

        jTextAreaCommentary.setBackground(new java.awt.Color(250, 240, 200));
        jTextAreaCommentary.setColumns(20);
        jTextAreaCommentary.setFont(new java.awt.Font("Georgia", 0, 13));
        jTextAreaCommentary.setLineWrap(true);
        jTextAreaCommentary.setRows(5);
        jTextAreaCommentary.setWrapStyleWord(true);
        jTextAreaCommentary.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusLost(java.awt.event.FocusEvent evt) {
                jTextAreaCommentaryFocusLost(evt);
            }
        });
        jScrollPane4.setViewportView(jTextAreaCommentary);

        org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(layout.createSequentialGroup()
                        .addContainerGap()
                        .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
                            .add(org.jdesktop.layout.GroupLayout.LEADING, layout.createSequentialGroup()
                                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                                    .add(jLabel1)
                                    .add(layout.createSequentialGroup()
                                        .add(10, 10, 10)
                                        .add(jScrollPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 176, Short.MAX_VALUE)))
                                .add(17, 17, 17)
                                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                                    .add(jLabel2)
                                    .add(layout.createSequentialGroup()
                                        .add(10, 10, 10)
                                        .add(jScrollPane2, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 177, Short.MAX_VALUE)))
                                .add(20, 20, 20)
                                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                                    .add(layout.createSequentialGroup()
                                        .add(10, 10, 10)
                                        .add(jScrollPane3, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 177, Short.MAX_VALUE))
                                    .add(jLabel3)))
                            .add(layout.createSequentialGroup()
                                .add(jLabel5)
                                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, 513, Short.MAX_VALUE))))
                    .add(layout.createSequentialGroup()
                        .add(20, 20, 20)
                        .add(jScrollPane4, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 587, Short.MAX_VALUE))
                    .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
                        .addContainerGap()
                        .add(jPanel1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .addContainerGap()
                .add(jPanel1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .add(48, 48, 48)
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(jLabel1)
                    .add(jLabel2)
                    .add(jLabel3))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(layout.createSequentialGroup()
                        .add(jScrollPane1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(jLabel5))
                    .add(jScrollPane2, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .add(jScrollPane3, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(jScrollPane4, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 282, Short.MAX_VALUE)
                .addContainerGap())
        );

        layout.linkSize(new java.awt.Component[] {jScrollPane1, jScrollPane2, jScrollPane3}, org.jdesktop.layout.GroupLayout.VERTICAL);

    }// </editor-fold>//GEN-END:initComponents

    private void jListRelatedFeatureMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jListRelatedFeatureMouseClicked
        addRelatedFeature();
        jPopupMenuRelatedFeature.show(jListRelatedFeature,evt.getX(),evt.getY());
    }//GEN-LAST:event_jListRelatedFeatureMouseClicked
    
    private void jListRelatedContextMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jListRelatedContextMouseClicked
        addRelatedContext();
        jPopupMenuRelatedContext.show(jListRelatedContext,evt.getX(),evt.getY());
    }//GEN-LAST:event_jListRelatedContextMouseClicked
    
    
     protected void addComponent() {
        
        final Feature _feature = Storage.getFeature();
        if (_feature != null){
            
            jPopupMenuComponent = new JPopupMenu();
            
            List <Context> lstContext = new ArrayList<Context>();
            //TODO obtenir els contexts dels sectors
            Iterator<Sector> iterSector = _feature.getSectors().iterator();
            while(iterSector.hasNext()){
                lstContext.addAll(Context.Inventory.getList(iterSector.next()));
            }
            //lstContext = Context.Inventory.getList();
            
            Iterator<Context> iter2 = lstContext.iterator();
            
            
            TreeSet <Context>contexts = new TreeSet();
            
            while(iter2.hasNext())
                contexts.add(iter2.next());
            
            iter2 = contexts.iterator();
            
            int size = contexts.size();
            
            
            if (size>10){
                int smenus = ((size-1)/10)+1;
                
                for (int j=1; j<=smenus; j++){
                    JMenu aJMenu= new JMenu();
                    StringBuffer buff = new StringBuffer();
                    
                    for(int i = 1; i<=10; i++){
                        
                        if (iter2.hasNext()){
                            final Context context= (Context) iter2.next();
                            if (context!=null){
                                //if (!context.isClosed()){
                                final JCheckBoxMenuItem jcheck = new JCheckBoxMenuItem();
                                jcheck.setText(context.toString());
                                
                                if (i==1)buff.append(context.toString()+"...");
                                if (i==10)buff.append(context.toString());
                                
                                Iterator <Context> iter4 = Context.Inventory.getList(_feature).iterator();
                                
                                while (iter4.hasNext()){
                                    Context acontext = (Context) iter4.next();
                                    if (context.equals(acontext))jcheck.setSelected(true);
                                }
                                
                                //if (sri.hasEquality(context, Storage.getContext()))
                                //    jcheck.setSelected(true);
                                
                                aJMenu.add(jcheck);
                                
                                jcheck.addMouseListener(new MouseAdapter(){
                                    public void mouseReleased(MouseEvent evt) {
                                        
                                        if(jcheck.getState()){
                                            //Afegim
                                            context.setFeature(_feature);
                                            
                                            AbstractInventory.setObject(context);
                                        }else{
                                            //Traiem
                                            context.setFeature(null);
                                            
                                            AbstractInventory.setObject(context);
                                        }//while
                                        fillComponent();
                                    }
                                    
                                });
                            }
                        }
                        aJMenu.setText(buff.toString());
                        jPopupMenuComponent.add(aJMenu);
                    }
                }
            } else while (iter2.hasNext()){
                final Context context= (Context) iter2.next();
                if (context!=null && context != null){
                    //if (!context.isClosed()){
                    final JCheckBoxMenuItem jcheck = new JCheckBoxMenuItem();
                    jcheck.setText(context.toString());
                    
                    
                    Iterator <Context> iter4 = _feature.getRelatedContexts().iterator();
                    while (iter4.hasNext()){
                        Context acontext = (Context) iter4.next();
                        if (context.equals(acontext))jcheck.setSelected(true);
                    }
                    
                    jPopupMenuComponent.add(jcheck);
                    
                    jcheck.addMouseListener(new MouseAdapter(){
                        public void mouseReleased(MouseEvent evt) {
                            
                            
                            if(jcheck.getState()){
                                            //Afegim
                                            context.setFeature(_feature);
                                            
                                            AbstractInventory.setObject(context);
                                        }else{
                                            //Traiem
                                            context.setFeature(null);
                                            
                                            AbstractInventory.setObject(context);
                            }//while
                            fillComponent();
                        }
                    });
                }
            }
        }
    }
    
    
    
    
    protected void addRelatedContext() {
        
        final Feature _feature = Storage.getFeature();
        if (_feature != null){
            
            jPopupMenuRelatedContext = new JPopupMenu();
            
            List <Context> lstContext;
            lstContext = Context.Inventory.getList();
            Iterator<Context> iter2 = lstContext.iterator();
            
            
            TreeSet <Context>contexts = new TreeSet();
            
            while(iter2.hasNext())
                contexts.add(iter2.next());
            
            iter2 = contexts.iterator();
            
            int size = contexts.size();
            
            
            if (size>10){
                int smenus = ((size-1)/10)+1;
                
                for (int j=1; j<=smenus; j++){
                    JMenu aJMenu= new JMenu();
                    StringBuffer buff = new StringBuffer();
                    
                    for(int i = 1; i<=10; i++){
                        
                        if (iter2.hasNext()){
                            final Context context= (Context) iter2.next();
                            if (context!=null && context != null){
                                //if (!context.isClosed()){
                                final JCheckBoxMenuItem jcheck = new JCheckBoxMenuItem();
                                jcheck.setText(context.toString());
                                
                                if (i==1)buff.append(context.toString()+"...");
                                if (i==10)buff.append(context.toString());
                                
                                Iterator <Context> iter4 = _feature.getRelatedContexts().iterator();
                                while (iter4.hasNext()){
                                    Context acontext = (Context) iter4.next();
                                    if (context.equals(acontext))jcheck.setSelected(true);
                                }
                                
                                //if (sri.hasEquality(context, Storage.getContext()))
                                //    jcheck.setSelected(true);
                                
                                aJMenu.add(jcheck);
                                
                                jcheck.addMouseListener(new MouseAdapter(){
                                    public void mouseReleased(MouseEvent evt) {
                                        
                                        if(jcheck.getState()){
                                            //Afegim
                                            _feature.getRelatedContexts().add(context);
                                            
                                            AbstractInventory.setObject(_feature);
                                        }else{
                                            //Traiem
                                            _feature.getRelatedContexts().remove(context);
                                            
                                            AbstractInventory.setObject(_feature);
                                        }//while
                                        fillRelatedContextField();
                                    }
                                    
                                });
                            }
                        }
                        aJMenu.setText(buff.toString());
                        jPopupMenuRelatedContext.add(aJMenu);
                    }
                }
            } else while (iter2.hasNext()){
                final Context context= (Context) iter2.next();
                if (context!=null && context != null){
                    //if (!context.isClosed()){
                    final JCheckBoxMenuItem jcheck = new JCheckBoxMenuItem();
                    jcheck.setText(context.toString());
                    
                    
                    Iterator <Context> iter4 = _feature.getRelatedContexts().iterator();
                    while (iter4.hasNext()){
                        Context acontext = (Context) iter4.next();
                        if (context.equals(acontext))jcheck.setSelected(true);
                    }
                    
                    jPopupMenuRelatedContext.add(jcheck);
                    
                    jcheck.addMouseListener(new MouseAdapter(){
                        public void mouseReleased(MouseEvent evt) {
                            
                            
                            if(jcheck.getState()){
                                //Afegim
                                _feature.getRelatedContexts().add(context);
                                
                                AbstractInventory.setObject(_feature);
                            }else{
                                //Traiem
                                _feature.getRelatedContexts().remove(context);
                                
                                AbstractInventory.setObject(_feature);
                            }//while
                            fillRelatedContextField();
                        }
                    });
                }
            }
        }
    }
    
    protected void addRelatedFeature() {
        
        final Feature _feature = Storage.getFeature();
        if (_feature != null){
            
            jPopupMenuRelatedFeature = new JPopupMenu();
            
            List <Feature> lstFeature;
            lstFeature = Feature.Inventory.getList();
            Iterator<Feature> iter2 = lstFeature.iterator();
            
            
            TreeSet <Feature>features = new TreeSet();
            
            while(iter2.hasNext())
                features.add(iter2.next());
            
            iter2 = features.iterator();
            
            int size = features.size();
            
            
            if (size>10){
                int smenus = ((size-1)/10)+1;
                
                for (int j=1; j<=smenus; j++){
                    JMenu aJMenu= new JMenu();
                    StringBuffer buff = new StringBuffer();
                    
                    for(int i = 1; i<=10; i++){
                        
                        if (iter2.hasNext()){
                            final Feature feature = (Feature) iter2.next();
                            if (feature!=null && feature != null){
                                //if (!context.isClosed()){
                                final JCheckBoxMenuItem jcheck = new JCheckBoxMenuItem();
                                jcheck.setText(feature.toString());
                                
                                if (i==1)buff.append(feature.toString()+"...");
                                if (i==10)buff.append(feature.toString());
                                
                                Iterator <Feature> iter4 = _feature.getRelatedFeatures().iterator();
                                while (iter4.hasNext()){
                                    Feature afeature = (Feature) iter4.next();
                                    if (feature.equals(afeature))jcheck.setSelected(true);
                                }
                                
                                aJMenu.add(jcheck);
                                
                                jcheck.addMouseListener(new MouseAdapter(){
                                    public void mouseReleased(MouseEvent evt) {
                                        
                                        if(jcheck.getState()){
                                            //Afegim
                                            _feature.getRelatedFeatures().add(feature);
                                            
                                            AbstractInventory.setObject(_feature);
                                        }else{
                                            //Traiem
                                            _feature.getRelatedFeatures().remove(feature);
                                            
                                            AbstractInventory.setObject(_feature);
                                        }//while
                                        fillRelatedFeatureField();
                                    }
                                    
                                });
                            }
                        }
                        aJMenu.setText(buff.toString());
                        jPopupMenuRelatedFeature.add(aJMenu);
                    }
                }
            } else while (iter2.hasNext()){
                final Feature feature = (Feature) iter2.next();
                if (feature!=null && feature != null){
                    //if (!context.isClosed()){
                    final JCheckBoxMenuItem jcheck = new JCheckBoxMenuItem();
                    jcheck.setText(feature.toString());
                    
                    
                    Iterator <Feature> iter4 = _feature.getRelatedFeatures().iterator();
                    while (iter4.hasNext()){
                        Feature afeature = (Feature) iter4.next();
                        if (feature.equals(afeature))jcheck.setSelected(true);
                    }
                    
                    jPopupMenuRelatedFeature.add(jcheck);
                    
                    jcheck.addMouseListener(new MouseAdapter(){
                        public void mouseReleased(MouseEvent evt) {
                            if(jcheck.getState()){
                                //Afegim
                                _feature.getRelatedFeatures().add(feature);
                                
                                AbstractInventory.setObject(_feature);
                            }else{
                                //Traiem
                                _feature.getRelatedFeatures().remove(feature);
                                
                                AbstractInventory.setObject(_feature);
                            }//while
                            fillRelatedFeatureField();
                        }
                    });
                }
            }
        }
    }
        
    private void jTextAreaCommentaryFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jTextAreaCommentaryFocusLost
        saveFeatureFields();
    }//GEN-LAST:event_jTextAreaCommentaryFocusLost
    
    private void jTextFieldActionMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTextFieldActionMouseClicked
        jPopupMenuActions.show(jTextFieldAction,evt.getX(),evt.getY());
    }//GEN-LAST:event_jTextFieldActionMouseClicked
    
    private void jTextFieldSectorMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTextFieldSectorMouseClicked
        jPopupMenuSectors.show(jTextFieldSector,evt.getX(),evt.getY());
    }//GEN-LAST:event_jTextFieldSectorMouseClicked

private void jListCompositionMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jListCompositionMouseClicked
    addComponent();
    jPopupMenuComponent.show(jListComposition,evt.getX(),evt.getY());
}//GEN-LAST:event_jListCompositionMouseClicked

private void jTextFieldFeatureTypeMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTextFieldFeatureTypeMouseClicked
        try {
            Field field = Feature.class.getDeclaredField("featureType");
            jPopupMenu = SidoraTools.generatePopupMenuCategory(Storage.getFeature(), field, jTextFieldFeatureType);
            jPopupMenu.show(jTextFieldFeatureType,evt.getX(),evt.getY());
            
            /*Per a permetre l'actualització del camp jTextFieldFeature al 
            * canviar el tipus de FET ha calgut que un SwingWorker esperi a que 
            * s'actualitzi la base d'objectes
            */
            SwingWorker worker = new SwingWorker() {
                @Override
                @SuppressWarnings("empty-statement")
                protected Boolean doInBackground() throws Exception {
                    while (jPopupMenu.isShowing()){
                        //do nothing
                    };
                    Thread.sleep(100);
                    System.out.println(Storage.getFeature().getName());
                    Feature feature = Storage.getFeature();
                    jTextFieldFeature.setText(feature.getName());
                    //fillFeatureItems();
                    return true;
                }
            };
            worker.execute();
         
        } catch (SecurityException ex) {
            ex.printStackTrace();
        } catch (NoSuchFieldException ex) {
            ex.printStackTrace();
        }
        
       
}//GEN-LAST:event_jTextFieldFeatureTypeMouseClicked
    
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JList jListComposition;
    private javax.swing.JList jListRelatedContext;
    private javax.swing.JList jListRelatedFeature;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JScrollPane jScrollPane4;
    private javax.swing.JTextArea jTextAreaCommentary;
    private javax.swing.JTextField jTextFieldAction;
    private javax.swing.JTextField jTextFieldFeature;
    private javax.swing.JTextField jTextFieldFeatureType;
    private javax.swing.JTextField jTextFieldSector;
    // End of variables declaration//GEN-END:variables
    private JPopupMenu jPopupMenu;
    private JPopupMenu jPopupMenuSectors;
    private JPopupMenu jPopupMenuActions;
    private JPopupMenu jPopupMenuRelatedContext;
    private JPopupMenu jPopupMenuRelatedFeature;
    private JPopupMenu jPopupMenuComponent;
    /**
     * Gets default instance. Do not use directly: reserved for *.settings files only,
     * i.e. deserialization routines; otherwise you could get a non-deserialized instance.
     * To obtain the singleton instance, use {@link findInstance}.
     */
    public static synchronized FeatureTopComponent getDefault() {
        if (instance == null) {
            instance = new FeatureTopComponent();
        }
        return instance;
    }
    
    /**
     * Obtain the FeatureTopComponent instance. Never call {@link #getDefault} directly!
     */
    public static synchronized FeatureTopComponent findInstance() {
        TopComponent win = WindowManager.getDefault().findTopComponent(PREFERRED_ID);
        if (win == null) {
            ErrorManager.getDefault().log(ErrorManager.WARNING, "Cannot find Feature component. It will not be located properly in the window system.");
            return getDefault();
        }
        if (win instanceof FeatureTopComponent) {
            return (FeatureTopComponent)win;
        }
        ErrorManager.getDefault().log(ErrorManager.WARNING, "There seem to be multiple components with the '" + PREFERRED_ID + "' ID. That is a potential source of errors and unexpected behavior.");
        return getDefault();
    }
    
    public int getPersistenceType() {
        return TopComponent.PERSISTENCE_ALWAYS;
    }
    
    public void componentOpened() {
        // TODO add custom code on component opening
    }
    
    public void componentClosed() {
        // TODO add custom code on component closing
    }
    
    /** replaces this in object stream */
    public Object writeReplace() {
        return new ResolvableHelper();
    }
    
    protected String preferredID() {
        return PREFERRED_ID;
    }
    
    void emptyFeaturetItems() {
        throw new UnsupportedOperationException("Not yet implemented");
    }
    
    
    public void fillFeatureItems() {
        emptyFeatureItems();
        
        Feature feature = Storage.getFeature();
        
        if (feature != null){
            jTextAreaCommentary.setText(feature.getCommentary());
            jTextFieldFeature.setText(feature.getName());
            if (feature.getFeatureType() != null){
             
                jTextFieldFeatureType.setText(feature.getFeatureType().getValue());
            }
            
            addSectorMenu();
            fillSectorField();
            
            addActionMenu();
            fillActionField();
            
            fillRelatedContextField();
            fillRelatedFeatureField();
            fillComponent();
        }
        
    }
    
    
    public void emptyFeatureItems(){
        jTextAreaCommentary.setText("");
        jTextFieldFeature.setText("");
        
        jTextFieldSector.setText("");
        jTextFieldAction.setText("");
    }
    
    
    final static class ResolvableHelper implements Serializable {
        private static final long serialVersionUID = 1L;
        public Object readResolve() {
            return FeatureTopComponent.getDefault();
        }
    }
    
    public void saveFeatureFields(){
        Feature feature = Storage.getFeature();
        
        if (feature != null){
            feature.setCommentary(jTextAreaCommentary.getText());
            AbstractInventory.setObject(feature);
        }
    }
    
    protected void fillSectorField() {
        Feature feature = Storage.getFeature();
        if (feature!=null){
            
            
            StringBuffer textbuffer = new StringBuffer("[");
            //Sector sector = context.getSectors().first();
            // System.out.println(sector);
            TreeSet set = feature.getSectors();
            boolean empty = set.isEmpty();
            Iterator iter = set.iterator();
            
            while (iter.hasNext()){
                Sector asector = (Sector) iter.next();
                textbuffer.append(asector.getIdSector().getZone().getIdZone().toString()
                +"."+asector.getIdSector().getNumber().toString());
                
                if (iter.hasNext())
                    textbuffer.append("/");
            }
            textbuffer.append("]");
            
            jTextFieldSector.setText(textbuffer.toString());
        }
        
        
    }
    
    protected void addSectorMenu() {
        
        final Feature feature = Storage.getFeature();
        if (feature!=null){
            
            jPopupMenuSectors= new JPopupMenu();
            Set <Sector>sectors = feature.getIdFet().getZone().getSectors();
            Iterator<Sector> iter2 = sectors.iterator();
            int size = sectors.size();
            
            
            if (size>10){
                int smenus = ((size-1)/10)+1;
                
                for (int j=1; j<=smenus; j++){
                    JMenu aJMenu= new JMenu();
                    StringBuffer buff = new StringBuffer();
                    
                    for(int i = 1; i<=10; i++){
                        
                        if (iter2.hasNext()){
                            final Sector sector= (Sector) iter2.next();
                            if (sector!=null){
                                if (!sector.isClosed()){
                                    final JCheckBoxMenuItem jcheck = new JCheckBoxMenuItem();
                                    jcheck.setText(sector.toString());
                                    
                                    if (i==1)buff.append(sector.getIdSector().getNumber().toString()+"...");
                                    if (i==10)buff.append(sector.getIdSector().getNumber().toString());
                                    
                                    Iterator <Sector> iter4 = feature.getSectors().iterator();
                                    while (iter4.hasNext()){
                                        Sector asector = (Sector) iter4.next();
                                        if (sector.equals(asector))jcheck.setSelected(true);
                                    }
                                    
                                    aJMenu.add(jcheck);
                                    
                                    jcheck.addMouseListener(new MouseAdapter(){
                                        public void mouseReleased(MouseEvent evt) {
                                            
                                            if(jcheck.getState()){
                                                
                                                feature.getSectors().add(sector);
                                                /*if  (feature.getFeature()!=null){
                                                    feature.getFeature().setSectors(feature.getSectors());
                                                }
                                                 
                                                sector.getContexts().add(feature);*/
                                            } else{
                                                
                                                feature.getSectors().remove(sector);
                                                /*if  (context.getFeature()!=null){
                                                    context.getFeature().setSectors(context.getSectors());
                                                }
                                                sector.getContexts().remove(context);*/
                                            }
                                            fillSectorField();
                                            addSectorMenu();
                                            
                                            AbstractInventory.setObject(feature);
                                        }
                                    });
                                }
                            }
                            
                        }
                    }
                    aJMenu.setText(buff.toString());
                    jPopupMenuSectors.add(aJMenu);
                    
                }
            } else while (iter2.hasNext()){
                final Sector sector= (Sector) iter2.next();
                if (sector!=null){
                    if (!sector.isClosed()){
                        final JCheckBoxMenuItem jcheck = new JCheckBoxMenuItem();
                        jcheck.setText(sector.toString());
                        
                        Iterator <Sector> iter4 = feature.getSectors().iterator();
                        while (iter4.hasNext()){
                            Sector asector = (Sector) iter4.next();
                            if (sector.equals(asector))jcheck.setSelected(true);
                        }
                        
                        jPopupMenuSectors.add(jcheck);
                        
                        jcheck.addMouseListener(new MouseAdapter(){
                            public void mouseReleased(MouseEvent evt) {
                                
                                if(jcheck.getState()){
                                    
                                    feature.getSectors().add(sector);
                                                /*if  (feature.getFeature()!=null){
                                                    feature.getFeature().setSectors(feature.getSectors());
                                                }
                                                 
                                                sector.getContexts().add(feature);*/
                                } else{
                                    
                                    feature.getSectors().remove(sector);
                                                /*if  (context.getFeature()!=null){
                                                    context.getFeature().setSectors(context.getSectors());
                                                }
                                                sector.getContexts().remove(context);*/
                                }
                                
                                fillSectorField();
                                addSectorMenu();
                                
                                AbstractInventory.setObject(feature);
                                
                            }
                        });
                    }
                }}
            
        }
        
    }
    
    protected void addActionMenu() {
        
        final Feature feature = Storage.getFeature();
        if (feature!=null){
            
            jPopupMenuActions = new JPopupMenu();
            List list = Action.Inventory.getList(Storage.getSite());
            TreeSet <Action> actions = new TreeSet<Action>();
            
            Iterator iter2 = list.iterator();
            while(iter2.hasNext()){
                actions.add((Action) iter2.next());
            }
            iter2 = actions.iterator();
            
            
            int size = actions.size();
            
            
            if (size>10){
                int smenus = ((size-1)/10)+1;
                
                for (int j=1; j<=smenus; j++){
                    JMenu aJMenu= new JMenu();
                    StringBuffer buff = new StringBuffer();
                    
                    for(int i = 1; i<=10; i++){
                        
                        if (iter2.hasNext()){
                            final Action action = (Action) iter2.next();
                            if (action!=null){
                                //if (!action.isClosed()){
                                final JCheckBoxMenuItem jcheck = new JCheckBoxMenuItem();
                                jcheck.setText(action.toString());
                                
                                if (i==1)buff.append(action.toString()+"...");
                                if (i==10)buff.append(action.toString());
                                
                                Iterator <Action> iter4 = feature.getArchactions().iterator();
                                while (iter4.hasNext()){
                                    Action aaction = (Action) iter4.next();
                                    if (action.equals(aaction))jcheck.setSelected(true);
                                }
                                
                                aJMenu.add(jcheck);
                                
                                jcheck.addMouseListener(new MouseAdapter(){
                                    public void mouseReleased(MouseEvent evt) {
                                        
                                        if(jcheck.getState()){
                                            feature.getArchactions().add(action);
                                        } else{
                                            feature.getArchactions().remove(action);
                                        }
                                        
                                        fillActionField();
                                        addActionMenu();
                                        
                                        AbstractInventory.setObject(feature);
                                    }
                                });
                                //}
                            }
                            
                        }
                    }
                    aJMenu.setText(buff.toString());
                    jPopupMenuActions.add(aJMenu);
                    
                }
            } else while (iter2.hasNext()){
                final Action action= (Action) iter2.next();
                if (action!=null){
                    //if (!sector.isClosed()){
                    final JCheckBoxMenuItem jcheck = new JCheckBoxMenuItem();
                    jcheck.setText(action.toString());
                    
                    Iterator <Action> iter4 = feature.getArchactions().iterator();
                    while (iter4.hasNext()){
                        Action aaction = (Action) iter4.next();
                        if (action.equals(aaction))jcheck.setSelected(true);
                    }
                    
                    
                    jPopupMenuActions.add(jcheck);
                    
                    jcheck.addMouseListener(new MouseAdapter(){
                        public void mouseReleased(MouseEvent evt) {
                            
                            if(jcheck.getState()){
                                feature.getArchactions().add(action);
                            } else{
                                feature.getArchactions().remove(action);
                            }
                            
                            fillActionField();
                            addActionMenu();
                            
                            AbstractInventory.setObject(feature);
                            
                        }
                    });
                    //}
                }}
            
        }
        
    }
    
    public void fillActionField() {
        Feature feature = Storage.getFeature();
        if (feature!=null){
            
            
            StringBuffer textbuffer = new StringBuffer("[");
            //Sector sector = context.getSectors().first();
            // System.out.println(sector);
            TreeSet set = feature.getArchactions();
            boolean empty = set.isEmpty();
            Iterator iter = set.iterator();
            
            while (iter.hasNext()){
                Action aaction = (Action) iter.next();
                textbuffer.append(aaction.toString());
                
                if (iter.hasNext())
                    textbuffer.append("/");
            }
            textbuffer.append("]");
            
            jTextFieldAction.setText(textbuffer.toString());
        }
    }
    
    public void fillRelatedContextField() {
        Feature feature = Storage.getFeature();
        DefaultListModel contextModel = new DefaultListModel();
        
        if (feature!=null){
            StringBuffer textbuffer = new StringBuffer("[");
            //Sector sector = context.getSectors().first();
            // System.out.println(sector);
            TreeSet set = feature.getRelatedContexts();
            boolean empty = set.isEmpty();
            Iterator iter = set.iterator();
            
            while (iter.hasNext()){
                Context context = (Context) iter.next();
                contextModel.addElement(context);
            }
            
            jListRelatedContext.setModel(contextModel);
        }
    }

        public void fillComponent() {
        Feature feature = Storage.getFeature();
        DefaultListModel contextModel = new DefaultListModel();
        
        if (feature!=null){
            TreeSet set = new TreeSet(Context.Inventory.getList(feature));
            Iterator iter = set.iterator();
            
            while (iter.hasNext()){
                Context context = (Context) iter.next();
                contextModel.addElement(context);
            }
            
            jListComposition.setModel(contextModel);
        }
    }
    
    
    public void fillRelatedFeatureField() {
        Feature feature = Storage.getFeature();
        DefaultListModel contextModel = new DefaultListModel();
        
        if (feature!=null){
            StringBuffer textbuffer = new StringBuffer("[");
            //Sector sector = context.getSectors().first();
            // System.out.println(sector);
            TreeSet set = feature.getRelatedFeatures();
            boolean empty = set.isEmpty();
            Iterator iter = set.iterator();
            
            while (iter.hasNext()){
                Feature feature2 = (Feature) iter.next();
                contextModel.addElement(feature2);
            }
            
            jListRelatedFeature.setModel(contextModel);
        }
    }
    
}// End class
